<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 客户列表 -->
      <div v-if="showCustomerList">
        <el-card>
          <el-form ref="searchFormRef" :model="searchForm" label-position="right" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item prop="customer_name" label="客户名称">
                  <el-input v-model="searchForm.customer_name" placeholder="请输入客户名称/客户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="customer_flow_up_status" label="跟进状态">
                  <el-select v-model="searchForm.customer_flow_up_status" placeholder="请选择跟进状态" style="width: 100%"
                    clearable>
                    <el-option label="客户比价中" value="1" />
                    <el-option label="客户觉得物流贵" value="2" />
                    <el-option label="报价后客户未读未回" value="3" />
                    <el-option label="报价后客户已读不回" value="4" />
                    <el-option label="客户暂无设计图纸" value="5" />
                    <el-option label="客户未提供报价信息" value="6" />
                    <el-option label="自定义" value="7" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="customer_main_chat_ways" label="沟通方式">
                  <el-select v-model="searchForm.customer_main_chat_ways" placeholder="请选择沟通方式" style="width: 100%">
                    <el-option label="邮箱" value="1" />
                    <el-option label="手机" value="2" />
                    <el-option label="微信" value="3" />
                    <el-option label="whatsApp" value="4" />
                    <el-option label="座机" value="5" />
                    <el-option label="QQ" value="6" />
                    <el-option label="平台账号" value="7" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item prop="customer_add_time" label="时间区间">
                  <el-date-picker v-model="searchForm.customer_add_time" type="daterange" align="right" unlink-panels
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    :picker-options="pickerOptions" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-row type="flex" justify="end">
                  <el-button type="success" icon="el-icon-search" size="medium" @click="handleSearch">查询</el-button>
                  <el-button type="success" icon="el-icon-search" size="medium" @click="handleReset">重置</el-button>
                </el-row>
              </el-col>
            </el-row>
            <!-- <el-row :gutter="20">
              <el-col :span="24">
                <el-row type="flex" justify="end">
                  <el-button type="success" icon="el-icon-search" size="medium"
                    >查询</el-button
                  >
                  <el-button type="success" icon="el-icon-search" size="medium"
                    >重置</el-button
                  >
                </el-row>
              </el-col>
            </el-row> -->
          </el-form>
        </el-card>
        <el-card style="margin-top: 20px; height: calc(100vh - 290px)">
          <!-- 新增 - 导出 - 删除按钮 -->
          <el-row :gutter="20" style="margin-bottom: 20px">
            <el-col :span="20">
              <el-button type="success" size="medium" @click="showCustomerPage">新增客户</el-button>
              <el-button size="medium" plain>导出</el-button>
              <el-button type="danger" size="medium" plain @click="handleBacthDelete">批量删除</el-button>
            </el-col>
            <el-col :span="2" :offset="2">
              <!-- <el-button type="primary" size="medium">创建订单</el-button> -->
            </el-col>
          </el-row>

          <!-- 客户列表表格 -->

          <vxe-grid ref="formRef" border background resizable max-height="480" align="center" :columns="tableColumn"
            :data="tableData" :loading="loading" :row-config="{ height: 43, isCurrent: true, isHover: true }"
            show-overflow @checkbox-change="checkboxChangeEvent" @checkbox-all="checkboxChangeEvent">
            <!-- 沟通方式 -->
            <template #grid_chat="{ row }">
              <span v-for="item in row.customer_main_chat_ways" :key="item.key">{{ item.value
              }}<span v-show="row.customer_main_chat_ways.length > 1">、</span></span>
            </template>
            <!-- 行操作按钮 -->
            <template #grid_opration="{ row, column, $rowIndex, $columnIndex }">
              <el-button v-for="(item, i) in optColumnButtonList" :key="'opt_' + row.id + '_' + i" type="text" @click="
                toolbarButtonCallBack(
                  row,
                  column,
                  $rowIndex,
                  $columnIndex,
                  item.clickFn
                )
              ">
                {{ item.title }}
              </el-button>
            </template>
            <!-- 分页器 -->
            <template #pager>
              <vxe-pager :layouts="[
                'Sizes',
                'PrevJump',
                'PrevPage',
                'Number',
                'NextJump',
                'FullJump',
                'Total',
              ]" :current-page.sync="tablePage.page_num" :page-size.sync="tablePage.page_amounts"
                :total="tablePage.total" @page-change="handlePageChange" />
            </template>
          </vxe-grid>
        </el-card>
      </div>

      <!-- 新增/编辑客户 -->
      <CustomerEdit v-if="showCustomerEdit" :customer-cid="customerCid" @goback="goback"
        @updateList="getCustomerDataList" />

      <!-- 客户详情  -->
      <CustomerDetail v-if="showCustomerDetail" :customer-cid="customerCid" @goback="goback" />

      <!-- 地址管理 -->
      <CustomerAddress v-if="showAddress" :customer-cid="customerCid" @goback="goback" />
      <!-- 开票管理 -->
      <CustomerInvoice v-if="showInvoice" :customer-cid="customerCid" @goback="goback" />
    </div>
  </div>
</template>

<script>
import CustomerEdit from './modules/CustomerEdit'
import CustomerDetail from './modules/CustomerDetail'
import CustomerAddress from './modules/CustomerAddress.vue'
import CustomerInvoice from './modules/CustomerInvoice.vue'
import {
  getCustomerListAPI,
  deleteCustomerAPI,
  deleteBatchCustomerAPI
} from '@/api/customer'
import { formatTime } from '@/utils/index'
import { thisExpression } from '@babel/types'
import { divide } from 'xe-utils'
import { formatDate } from '@/utils/index'
export default {
  components: {
    CustomerEdit,
    CustomerDetail,
    CustomerAddress,
    CustomerInvoice
  },
  data() {
    return {
      showCustomerList: true,
      showCustomerEdit: false,
      showCustomerDetail: false,
      showAddress: false,
      showInvoice: false,
      searchForm: {
        customer_name: '',
        customer_flow_up_status: '',
        customer_main_chat_ways: '',
        customer_add_time: ''
      },

      loading: false,
      // table列
      tableColumn: [
        { type: 'checkbox', width: 50 },
        { type: 'seq', title: '序号', width: 60 },
        { field: 'customer_add_time', title: '新增日期', width: 200 },
        { field: 'customer_owner', title: '业务员', width: 80 },
        { field: 'customer_name', title: '客户', width: 200 },
        {
          field: 'customer_main_chat_ways',
          title: '主要沟通方式',
          width: 200,
          slots: { default: 'grid_chat' }
        },
        { field: 'customer_flow_up_status', title: '跟进状态', width: 200 },
        { field: 'customer_last_flow_time', title: '最后跟进时间', width: 200 },
        { field: 'customer_mark_msg', title: '备注', width: 200 },
        {
          field: '',
          title: '操作',
          width: 300,
          fixed: 'right',
          slots: { default: 'grid_opration' }
          // slots: {
          //   default: ({ row }) => {
          //       return [
          //         <div>
          //           <vxe-button size="mini" status="primary" >查看</vxe-button>
          //           <vxe-button size="mini" status="warning">编辑</vxe-button>
          //           <vxe-button size="mini" status="danger">删除</vxe-button>
          //         </div>
          //       ]
          //   }
          // }
        }
      ],
      tableData: [], // table数据
      // 分页器配置
      tablePage: {
        page_num: 1,
        page_amounts: 10,
        total: 0
      },
      // 列表的操作按钮
      optColumnButtonList: [
        { type: 'view', title: '查看', clickFn: this.handleView },
        { type: 'edit', title: '编辑', clickFn: this.handleEdit },
        { type: 'address', title: '地址管理', clickFn: this.handleAddress },
        { type: 'invoice', title: '开票管理', clickFn: this.handleInvoice },
        { type: 'delete', title: '删除', clickFn: this.handleDelete }
      ],
      // 快捷时间选择
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },

      // 复选框
      isAllChecked: false,
      isIndeterminate: false,
      selectRecords: [],

      // 客户CID
      customerCid: ''
    }
  },

  created() {
    this.getCustomerDataList(this.tablePage)
  },

  methods: {
    // 点击新增客户按钮, 显示新增客户页面
    showCustomerPage() {
      this.showCustomerList = false
      this.showCustomerEdit = true
      this.customerCid = ''
    },

    // 返回
    goback() {
      this.showCustomerList = true
      this.showCustomerEdit = false
      this.showCustomerDetail = false
      this.showAddress = false
      this.showInvoice = false
    },

    // 点击编辑
    async handleEdit(row) {
      this.showCustomerList = false
      this.showCustomerEdit = true
      this.customerCid = row.customer_cid
    },

    // 点击详情
    handleView(row) {
      this.showCustomerList = false
      this.showCustomerDetail = true
      this.customerCid = row.customer_cid
    },

    // 点击地址
    handleAddress(row) {
      this.showCustomerList = false
      this.showAddress = true
      this.customerCid = row.customer_cid
    },

    // 点击开票
    handleInvoice(row) {
      this.showCustomerList = false
      this.showInvoice = true
      this.customerCid = row.customer_cid
    },

    // 获取客户列表
    async getCustomerDataList(data) {
      this.loading = true
      const res = await getCustomerListAPI({
        page_num: this.tablePage.page_num,
        page_amounts: this.tablePage.page_amounts,
        customer_name: this.searchForm.customer_name,
        customer_flow_up_status: this.searchForm.customer_flow_up_status,
        customer_main_chat_ways: this.searchForm.customer_main_chat_ways,
        customer_add_start_time:
          data && data.customer_add_start_time !== 'NaN-NaN-NaN'
            ? data && data.customer_add_start_time
            : '',
        customer_add_end_time:
          data && data.customer_add_end_time !== 'NaN-NaN-NaN'
            ? data && data.customer_add_end_time
            : ''
      })
      const dataStr = JSON.stringify(res.data_list)
      const deepData = JSON.parse(dataStr)
      // 数据显示改造
      deepData.map((item, index) => {
        // 跟进状态回显改造
        // 跟进状态： 客户比价中  客户觉得物流贵  报价后客户未读未回  报价后客户已读不回  客户暂无设计图纸  客户未提供报价信息   自定义
        if (item.customer_flow_up_status === '1') {
          item.customer_flow_up_status = '客户比价中'
        } else if (item.customer_flow_up_status === '2') {
          item.customer_flow_up_status = '客户觉得物流贵'
        } else if (item.customer_flow_up_status === '3') {
          item.customer_flow_up_status = '报价后客户未读未回'
        } else if (item.customer_flow_up_status === '4') {
          item.customer_flow_up_status = '报价后客户已读不回'
        } else if (item.customer_flow_up_status === '5') {
          item.customer_flow_up_status = '客户暂无设计图纸'
        } else if (item.customer_flow_up_status === '6') {
          item.customer_flow_up_status = '客户未提供报价信息'
        } else if (item.customer_flow_up_status === '7') {
          item.customer_flow_up_status = '自定义'
        }
        // 主要沟通方式 - 转数组
        item.customer_main_chat_ways = item.customer_main_chat_ways.split(',')
        // item.customer_contact_ways = JSON.parse(item.customer_contact_ways);
      })
      const obj = {
        1: '邮箱',
        2: '手机',
        3: '微信',
        4: 'WhatsApp',
        5: '座机',
        6: 'QQ',
        7: '平台账号'
      }
      // 主要沟通方式 - 翻译
      deepData.forEach((item) => {
        item.customer_main_chat_ways = item.customer_main_chat_ways.map((v) => {
          return {
            key: v,
            value: obj[v]
          }
        })
      })
      this.tableData = deepData
      this.loading = false
      this.tablePage.total = res.data_total
    },

    // 列表中的操作按钮触发的回调
    toolbarButtonCallBack(row, column, rowIndex, columnIndex, clickFn) {
      if (clickFn) {
        window.setTimeout(() => {
          clickFn(row, column, rowIndex, columnIndex)
        }, 50)
      }
    },

    // 切换分页
    async handlePageChange(row) {
      this.tablePage.page_num = row.currentPage
      this.tablePage.page_amounts = row.pageSize
      this.getCustomerDataList(this.tablePage)
    },

    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deleteCustomerAPI({ cid: row.customer_cid })
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getCustomerDataList()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 标准日转化为年月日
    transformTime(date) {
      var d = new Date(date)
      var datetime =
        d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
      return datetime
    },

    // 查询
    handleSearch() {
      const customer_add_start_time = formatDate(
        this.searchForm.customer_add_time[0],
        1
      )
      const customer_add_end_time = formatDate(
        this.searchForm.customer_add_time[1],
        1
      )
      console.log('customer_add_start_time  ----->  ', customer_add_start_time)
      console.log('customer_add_end_time  ----->  ', customer_add_end_time)
      this.tablePage.page_num = 1
      this.getCustomerDataList({
        page_num: this.tablePage.page_num,
        page_amounts: this.tablePage.page_amounts,
        customer_name: this.searchForm.customer_name,
        customer_flow_up_status: this.searchForm.customer_flow_up_status,
        customer_main_chat_ways: this.searchForm.customer_main_chat_ways,
        customer_add_start_time: customer_add_start_time,
        customer_add_end_time: customer_add_end_time
      })
    },
    // 重置
    handleReset() {
      this.$refs.searchFormRef.resetFields()
      this.getCustomerDataList()
    },

    // 批量删除
    checkboxChangeEvent() {
      const $grid = this.$refs.formRef
      this.isAllChecked = $grid.isAllCheckboxChecked()
      this.isIndeterminate = $grid.isAllCheckboxIndeterminate()
      this.selectRecords = $grid.getCheckboxRecords()
    },
    async handleBacthDelete() {
      if (this.selectRecords.length === 0) {
        this.$message.warning('请选择要删除的数据')
        return
      }
      const cids = this.selectRecords.map((item) => {
        return item.customer_cid
      })
      const res = await deleteBatchCustomerAPI({ cids })
      if (res.code === 200) {
        this.$message.success('操作成功')
        this.getCustomerDataList()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-link {
  margin-right: 5px;
}

.el-pagination {
  margin-top: 20px;
}

::v-deep .el-button--success {
  background-color: #1fcaa4;
  border-color: #1fcaa4;
}
</style>
